package com.wuyan.web.form.helper;

import com.wuyan.web.base.entity.PubConfig;
import com.wuyan.web.base.helper.PubConfigHelper;
import org.apache.commons.lang3.StringUtils;
import org.apdplat.word.WordSegmenter;
import org.apdplat.word.segmentation.Word;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.*;

import static com.wuyan.web.form.service.FormService.*;

/**
 * 分词工具
 */

@Component
public class WordStorageHelper {

    private static final String CONFIG_SYSTEM_FORM_WORD_NAME = "form-word";
    private static final String CONFIG_SYSTEM_FORM_WORD_LEN_NAME = "form-word-len";
    private static final String CONFIG_SYSTEM_FORM_WORD_SAVE_PATH_NAME = "form-word-storage-path";
    private static final String CONFIG_SYSTEM_FORM_FULL_TEXT = "full-text";
    public static final String WORD_TAGS_NAME = "cfg_tags";
    public static final String FULL_TEXT_NAME = "cfg_text_tag";

    @Autowired
    private PubConfigHelper configHelper;

    @Value("${wuyan.form.word}")
    private boolean word;

    @Value("${wuyan.form.word-len}")
    private int wordLen;

    @Value("${wuyan.form.full-text}")
    private boolean fullText;

    private WordStoragePathTypeEnum wordStoragePathTypeEnum;

    /**
     * 全文检索
     * @param form 原始数据
     */
    public void fullText(Map<String, Object> form) {
        final String[] fullText = {""};

        form.forEach((key, value) -> {
            if (key.equals(DEF_CREATE_TIME_NAME)
                    || key.equals(DEF_OPERATE_TIME_NAME)
                    || key.equals(DEF_CFG_STATUS_NAME)
                    || key.equals(DEF_CFG_SOURCE_NAME)
                    || key.equals(DEF_CREATOR_ID_NAME)
                    || key.equals(DEF_ID_NAME)
                    || key.equals(DEF_MONGO_ID_NAME)
                    || key.equals(DEF_CFG_FLOW_ID_NAME)
                    || key.equals(DEF_PARENT_ID_NAME)
                    || key.equals(FULL_TEXT_NAME)
            ) {
            } else {
                String v = null == value ? "" : value.toString();
                fullText[0] += v;
            }
        });

        form.put(FULL_TEXT_NAME, fullText[0]);
    }

    /**
     * 分词
     *
     * @param form 原数据
     * @return 结果
     */
    public Map<String, Object> word(Map<String, Object> form) {
        Map<String, Object> data = new HashMap<>();
        Set<String> tags = new HashSet<>();

        form.forEach((key, value) -> {
            if (key.equals(DEF_CREATE_TIME_NAME)
                    || key.equals(DEF_OPERATE_TIME_NAME)
                    || key.equals(DEF_CFG_STATUS_NAME)
                    || key.equals(DEF_CFG_SOURCE_NAME)
                    || key.equals(DEF_CREATOR_ID_NAME)
                    || key.equals(DEF_CREATOR_NAME_NAME)
                    || key.equals(DEF_ID_NAME)
                    || key.equals(DEF_MONGO_ID_NAME)
                    || key.equals(DEF_CFG_FLOW_ID_NAME)
                    || key.equals(DEF_PARENT_ID_NAME)
            ) {
                data.put(key, value);
            } else {
                String v = null == value ? "" : value.toString();
                if (v.length() >= getWordLen() && !StringUtils.isNumericSpace(v)) {
                    List<Word> words = WordSegmenter.seg(v);
                    words.forEach(word -> tags.add(word.getText()));
                }
            }
        });

        data.put(WORD_TAGS_NAME, tags);

        return data;
    }

    /**
     * 分词功能状态
     *
     * @return boolean
     */
    public boolean getWord() {
        List<PubConfig> configs = configHelper.configs("system", CONFIG_SYSTEM_FORM_WORD_NAME);
        return configs.size() > 0 ? Boolean.parseBoolean(configs.get(0).getCfgValue()) : word;
    }

    public boolean getFullText(){
        List<PubConfig> configs = configHelper.configs("system", CONFIG_SYSTEM_FORM_FULL_TEXT);
        return configs.size() > 0 ? Boolean.parseBoolean(configs.get(0).getCfgValue()) : fullText;
    }

    /**
     * 分词开始的字符串长度的起始条件
     *
     * @return int
     */
    private int getWordLen() {
        List<PubConfig> configs = configHelper.configs("system", CONFIG_SYSTEM_FORM_WORD_LEN_NAME);
        return configs.size() > 0 ? Integer.parseInt(configs.get(0).getCfgValue()) : wordLen;
    }

    /**
     * 分词存储的位置：local（当前集合），new（开辟一个新的集合单独存储），all（local和new的共生态）
     *
     * @return String
     */
    public WordStoragePathTypeEnum getWordSavePath() {
        List<PubConfig> configs = configHelper.configs("system", CONFIG_SYSTEM_FORM_WORD_SAVE_PATH_NAME);
        return configs.size() > 0 ? getWordStoragePathTypeEnum(configs.get(0).getCfgValue()) : wordStoragePathTypeEnum;
    }

    @Value("${wuyan.form.word-storage-path}")
    public void setWordStoragePathTypeEnum(String value) {
        this.wordStoragePathTypeEnum = getWordStoragePathTypeEnum(value);
    }

    /**
     * 根据value获取存储类型的枚举
     *
     * @param value 值
     * @return WordStoragePathTypeEnum
     */
    private WordStoragePathTypeEnum getWordStoragePathTypeEnum(String value) {
        if (WordStoragePathTypeEnum.LOCAL.getValue().equals(value)) {
            return WordStoragePathTypeEnum.LOCAL;
        } else if (WordStoragePathTypeEnum.NEW.getValue().equals(value)) {
            return WordStoragePathTypeEnum.NEW;
        } else {
            return WordStoragePathTypeEnum.ALL;
        }
    }
}
